from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from django.db.models import Count, Q
from .models import Log
from .serializers import LogSerializer


class LogPagination(PageNumberPagination):
    page_size = 20
    page_size_query_param = 'size'
    max_page_size = 200


class LogViewSet(viewsets.ModelViewSet):
    queryset = Log.objects.all()
    serializer_class = LogSerializer
    pagination_class = LogPagination
    
    def get_queryset(self):
        queryset = Log.objects.all()
        
        # 按级别过滤
        level = self.request.query_params.get('level')
        if level:
            queryset = queryset.filter(level=level)
        
        # 按来源过滤
        source = self.request.query_params.get('source')
        if source:
            queryset = queryset.filter(source=source)
        
        # 按时间范围过滤
        start_date = self.request.query_params.get('start_date')
        end_date = self.request.query_params.get('end_date')
        if start_date:
            queryset = queryset.filter(timestamp__gte=start_date)
        if end_date:
            queryset = queryset.filter(timestamp__lte=end_date)
        
        # 按关键词搜索
        keyword = self.request.query_params.get('keyword')
        if keyword:
            queryset = queryset.filter(
                Q(message__icontains=keyword) |
                Q(user__username__icontains=keyword)
            )
        
        return queryset.order_by('-timestamp')
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取日志统计信息"""
        # 总数统计
        total = Log.objects.count()
        
        # 按级别统计
        level_stats = Log.objects.values('level').annotate(count=Count('level'))
        level_counts = {item['level']: item['count'] for item in level_stats}
        
        # 按来源统计
        source_stats = Log.objects.values('source').annotate(count=Count('source'))
        source_counts = {item['source']: item['count'] for item in source_stats}
        
        # 构建统计数据
        stats = {
            'total': total,
            'success': level_counts.get('INFO', 0),
            'failed': level_counts.get('ERROR', 0),
            'error': level_counts.get('ERROR', 0),  # 与前端期望的字段保持一致
            'warning': level_counts.get('WARNING', 0),
            'debug': level_counts.get('DEBUG', 0),
            'level_distribution': level_counts,
            'source_distribution': source_counts
        }
        
        return Response(stats)
    
    @action(detail=False, methods=['post'])
    def create_log(self, request):
        """创建日志条目"""
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save(user=request.user if request.user.is_authenticated else None)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    def create(self, request, *args, **kwargs):
        """重写create方法，自动设置用户"""
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save(user=request.user if request.user.is_authenticated else None)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)